#include <kieper/channels/UdpRpcChannel.hpp>

#include <string>

#include <boost/lexical_cast.hpp>

namespace kieper {
namespace channels {

using boost::lexical_cast;
using boost::asio::io_service;
using boost::asio::ip::udp;

UdpRpcChannel::UdpRpcChannel(char* host, unsigned int port) : sock_(getIoService()) {
    io_service& io = getIoService();
    udp::resolver resolver(io);
    udp::resolver::query query(udp::v4(), host, (lexical_cast<std::string>(port)).c_str());
    udp::endpoint endpoint = *resolver.resolve(query);
    sock_.connect(endpoint);
}

UdpRpcChannel::~UdpRpcChannel() {
    sock_.close();
}

void UdpRpcChannel::doSend(unsigned char *message, size_t msgLen) {
    unsigned char buf[100];
    sock_.send(boost::asio::buffer(message, msgLen));
    int recvLen = sock_.receive(boost::asio::buffer(buf));
    onPacketReceived(buf, recvLen);
}


}
}
